from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
import logging
from .models import TaskInfo
from .serializers import TaskInfoModelSerializer
from .task_running import task_run
from django.db.utils import ProgrammingError, OperationalError

logging = logging.getLogger("log")


class SchedulerSingleton:
    _instance = None
    _scheduler = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._scheduler = BackgroundScheduler()
            cls._instance._add_tasks_to_scheduler()
            cls._scheduler.start()
        return cls._instance

    def _add_tasks_to_scheduler(self):
        logging.info("====任务开始初始化====")
        try:
            for task in TaskInfo.objects.all():
                task_model = TaskInfoModelSerializer(task).data
                if task.cron_expression:
                    # 你可能需要使用其他机制来定义和引用任务函数
                    self._scheduler.add_job(
                        task_run,
                        trigger=CronTrigger.from_crontab(task.cron_expression),
                        id=str(task.id),
                        args=(task_model,)
                    )
                    if not task.status:
                        self.pause_task(str(task.id))
        except (ProgrammingError, OperationalError) as e:
            logging.warning(f"数据库表TaskInfo可能未创建或无法访问: {e}")
            logging.info("由于表不存在或无法访问，任务初始化跳过。")

        logging.info("所有task：{}".format(self._scheduler.get_jobs()))
        logging.info("====任务初始化完成====")
        # 其他方法，如添加、删除、暂停、恢复任务等...

    def pause_task(self, task_id):
        self._scheduler.pause_job(job_id=task_id)

    def resume_task(self, task_id):
        self._scheduler.resume_job(job_id=task_id)

    def remove_task(self, task_id):
        self._scheduler.remove_job(job_id=task_id)
        logging.info("删除后，剩下task：{}".format(self._scheduler.get_jobs()))

    def modify_task(self, task_id, cron_expression):
        self._scheduler.modify_job(job_id=task_id, trigger=CronTrigger.from_crontab(cron_expression))

    @property
    def scheduler(self):
        return self._scheduler


# 获取调度器实例的便捷方法
def get_scheduler():
    return SchedulerSingleton()
